package org.lightcommons.orm.hibernate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jason Green
 * @since 2007-10-10
 */
public class HqlBuilder {
//	String current="";
//	from,where,orderby
	String select="";
	String count="*";
	StringBuffer from = new StringBuffer();
	List<Condition> conditions = new ArrayList<Condition>();
	StringBuffer orderby = new StringBuffer();
	public HqlBuilder select(String hql){
		if(hql!=null && !"".equals(hql.trim()))
			select = "select "+hql+" ";
		else
			select = "";
		return this;
	}
	
	public HqlBuilder from(String hql){
		from.append("from ").append(hql);
		return this;
	}
	
	public HqlBuilder asc(String field){
		return orderBy(field,true);
	}
	
	public HqlBuilder desc(String field){
		return orderBy(field,false);
	}
	
	public HqlBuilder orderBy(String field,boolean asc){
		if(field ==null || field.length()==0)
			return this;
		if(orderby.length() != 0){
			orderby.append(",");
		}
		orderby.append(asc ? field : field+" desc");
		return this;
	}
	
	public HqlBuilder addWhere(String hql){
		
		conditions.add(new HqlCondition(hql));
		return this;
	}
	
	public ConditionGroup andGroup(){
		ConditionGroup g = new ConditionGroup(false);
		conditions.add(g);
		return g;
	}
	
	public ConditionGroup orGroup(){
		ConditionGroup g = new ConditionGroup(true);
		conditions.add(g);
		return g;
	}
	
	public HqlBuilder addKeywords(String[] keywords,String namePerfix,String[] fields){
		conditions.add(new KeywordCondition(keywords,namePerfix,fields));
		return this;
	}
	
	public HqlBuilder count(String count){
		this.count = count;
		return this;
	}
	
	public StringBuffer getFromWhere(){
		StringBuffer result=new StringBuffer();
		result.append(from);
		if(!conditions.isEmpty()){
			StringBuffer b = new StringBuffer();
			for (Condition c : conditions) {
				if (c.toString() == null || c.toString().length() == 0)
					continue;
				if (b.length() != 0)
					b.append(" and ");
				b.append(c);
			}
			if(b.length() != 0){
				result.append(" where ").append(b);
			}
		}
		return result;
	}
	
	public String getQuery(){
		StringBuffer result = new StringBuffer();
		result.append(select);
		result.append(getFromWhere());
		if(orderby.length()!=0){
			result.append(" order by ").append(orderby);
		}
		return result.toString();
	}
	
	public String getCountQuery(){
		return "select count("+count+") "+getFromWhere();
	}
	
	@Override
	public String toString() {
		return getQuery();
	}
	
}
